#include <combineImage.h>

int combineImage(std::vector<cv::Mat> images, std::vector<cv::Point> points, cv::Mat &combinedImg)
{

  //check images overlapped
  for(uint i = 0; i < images.size() - 1; i++)
    {
      for(uint j = i + 1; j < images.size(); j++)
      	{
      	  if (overlapedImage(images[i], images[j], points[i], points[j]))
      	    {
	      return 0;
      	    }
      	}
    }

  cv::Size maxSize;
  calcMaxRC(images, points, maxSize);
  combinedImg = Mat::zeros(maxSize, CV_8UC3);
  Rect roiRect;
  for(uint i = 0; i < images.size(); i++)
    {
      roiRect.x = points[i].x;
      roiRect.y = points[i].y;
      roiRect.width = images[i].cols;
      roiRect.height = images[i].rows;
      Mat roi(combinedImg, roiRect);
      images[i].copyTo(roi);
      roiRect.x += images[i].cols;
    }

  return 0;

}

int overlapedImage(cv::Mat image1, cv::Mat image2, cv::Point point1, cv::Point point2)
{
  int flag = 0;
  if(point1.x < point2.x)
    {
      if(point1.x + image1.cols > point2.x)
	flag = 1;
    }
  else
    {
      if(point2.x + image2.cols > point1.x)
	flag = 1;
    }
  if(point1.y < point2.y)
    {
      if(point1.y + image1.rows > point2.y && flag == 1)
	flag = -1;
    }
  else
    {
      if(point2.y + image2.rows > point1.y && flag == 1)
	flag = -1;
    }

  if(flag == -1)
    {
      std::cout << "One image overlaped others." << std::endl;
      return 1;
    }
  else
    {
      return 0;
    }
}

void calcMaxRC(std::vector<cv::Mat> images, std::vector<cv::Point> points, cv::Size &size)
{
  int maxR,maxC;
  maxR = maxC = 0;
  for(uint i = 0; i < images.size(); i++)
    {
      int col = images[i].cols + points[i].x;
      int row = images[i].rows + points[i].y;
      if(maxC < col) maxC = col;
      if(maxR < row) maxR = row;
      size = cv::Size(maxC, maxR);
    }

}
